import { defineStore } from 'pinia'
import { getUserInfoApi } from '@/api/auth'
import { getUserListApi, addUserApi, updateUserApi, deleteUserApi } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    list: []
  }),
  actions: {
    async fetchUser() {
      try {
        const res = await getUserInfoApi()
        let user = res?.data ?? res?.user ?? res
        this.user = user
        console.log("xxxxxxxx", user)
        return user
      } catch (err) {
        this.user = null
        localStorage.removeItem('token')
        throw err
      }
    },
    logout() {
      localStorage.removeItem('token')
      this.user = null
      this.list = []
    },
    async fetchUserList() {
      const res = await getUserListApi()
      const list = res?.data ?? res?.users ?? res
      this.list = Array.isArray(list) ? list : []
      return this.list
    },
    async addUser(data) {
      const res = await addUserApi(data)
      const user = res?.data ?? res
      this.list.push(user)
      return user
    },
    async updateUser(id, data) {
      const res = await updateUserApi(id, data)
      const updated = res?.data ?? res
      const index = this.list.findIndex(u => u.id === id)
      if (index !== -1) this.list[index] = updated
      if (this.user?.id === id) this.user = { ...this.user, ...updated }
      return updated
    },
    async deleteUserById(id) {
      await deleteUserApi(id)
      this.list = this.list.filter(u => u.id !== id)
      if (this.user?.id === id) {
        this.logout()
        window.location.href = '/login'
      }
    }
  }
})
